package cn.jbolt.core.gen;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用于生成oracle里的对应序列和触发器
 *
 * @ClassName: OracleInitSqlGen
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2019年12月15日
 */
public class JBoltOracleInitSqlGen {
	private static final String packageName = "cn.jbolt.common.model.base";

	public static void genSequenceSql(Set<Class<?>> classes) {
		classes.stream().sorted(new Comparator<Class<?>>() {
			@Override
			public int compare(Class<?> o1, Class<?> o2) {
				return o1.getSimpleName().compareToIgnoreCase(o2.getSimpleName());
			}
		}).forEach(clazz -> {
			System.out.println(String.format(
					"create sequence %s_idsq\n" + "minvalue 10000\n" + "maxvalue 9999999999999999999999999999\n"
							+ "start with 10001\n" + "increment by 1\n" + "cache 20;",
					StrUtil.toSymbolCase(clazz.getSimpleName().replace("Base", "jb"), '_')));
		});
	}

	public static void genTriggerSql(Set<Class<?>> classes) {

		List<Class<?>> clazzs = classes.stream().sorted(new Comparator<Class<?>>() {
			@Override
			public int compare(Class<?> o1, Class<?> o2) {
				return o1.getSimpleName().compareToIgnoreCase(o2.getSimpleName());
			}
		}).collect(Collectors.toList());
		String objName;
		String tableName;
		for (Class<?> clazz : clazzs) {
			objName = StrUtil.toSymbolCase(clazz.getSimpleName().replace("Base", ""), '_');
			tableName = StrUtil.toSymbolCase(clazz.getSimpleName().replace("Base", "jb"), '_');
			System.out.println(String.format(
					"create or replace trigger %s_nxtid_tg\r\n" + "before insert on %s for each row\r\n" + "begin\r\n"
							+ "select %s_id_seq.nextval into:new.id from dual;\r\n" + "end;",
					objName, tableName, objName));
		}
	}

	public static void gen() {
		Set<Class<?>> classes = ClassUtil.scanPackage(packageName);
		genSequenceSql(classes);
//		genTriggerSql(classes);
	}

	public static void main(String[] args) {
		JBoltOracleInitSqlGen.gen();
	}
}
